package com.copm.ifm.common.mq.rabbit.confirm;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RabbitConsumer {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate template;

    @RabbitHandler
    //@RabbitListener(queues = RabbitConstants.Queue.IFM_HANDLER)
    //@RabbitListener(queues = RabbitConstants.Queue.EXCEPTION_HANDLER,ackMode = "MANUAL")
    public void onOrderMessage(Message message, Channel channel) throws Exception {
        //int i = 1/0;
        System.out.println(message);
        String messageId = message.getMessageProperties().getMessageId();
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("接收导的消息为：" + msg + "==消息id为：" + messageId);

        if (null == messageId) {
            System.out.println("消息id为null!");
            return;
        }
        //手动ACK
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        if (redisTemplate.opsForValue().setIfAbsent(messageId, new String(message.getBody()))) {
            // 代表第一次消费消息
            System.out.println("消息消费成功: " + new String(message.getBody()));
        } else {
            System.out.println("消息已经被消费过了!");
        }
    }
}
